<template>
  <el-dialog
      v-if="openForm"
      v-model="openBoole"
      :close-on-click-modal="false"
      :title="title"
      custom-class="mydialog"
      width="50%"
      @close="close"
  >
    <el-form
        ref="openRef"
        :model="openForm"
        :rules="rules"
        label-width="140px"
        size="small"
    >
      <el-row gutter="40">
        <el-col :span="24">
          <item-title title="基本信息"/>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="代理商名称"
              prop="agent.agentName"
          >
            <el-input
                v-model="openForm.agent.agentName"
                clearable
                placeholder="请输入代理商名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="代理商编号"
              prop="agent.agentNumber"
          >
            <el-input
                v-model="openForm.agent.agentNumber"
                clearable
                disabled
                placeholder="请输入代理商编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="统一社会信用代码"
              prop="agent.creditCode"
          >
            <el-input
                v-model="openForm.agent.creditCode"
                clearable
                placeholder="请输入统一社会信用代码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="代理商级别"
              prop="agent.agentLevel"
          >
            <el-select
                v-model="openForm.agent.agentLevel"
                placeholder="请选择代理商级别"
                style="width: 100%"
            >
              <el-option
                  v-for="item in agentlevelData"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="所在地区"
              prop="value"
          >
            <el-cascader
                v-model="openForm.value"
                :options="cityList"
                :popper-append-to-body="false"
                :props="{ value:'regionCode',label:'regionName' }"
                placeholder="请选择地区"
                style="width:100%"
                @change="handlCity"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="详细地址"
              prop="agent.address"
          >
            <el-input
                v-model="openForm.agent.address"
                clearable
                placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="联系人"
              prop="agent.userName"
          >
            <el-input
                v-model="openForm.agent.userName"
                clearable
                placeholder="请输入联系人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
              label="联系电话"
              prop="agent.tel"
          >
            <el-input
                v-model="openForm.agent.tel"
                clearable
                placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
              label="营业执照"
              prop="agent.businessLicenseFiles"
          >
            <div class="qualityFiles-container">
              <div
                  v-for="(item,index) in openForm.agent.businessLicenseFiles"
                  :key="index"
                  class="file-item"
              >
                <image-upload-view :data="item"/>
              </div>
            </div>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <div
          class="dialog-footer"
          style="display:flex;justify-content:center;align-items:center;"
      >
        <el-button
            class="border-btn"
            size="small"
            style="margin-right: 20px;"
            @click="close"
        >取消
        </el-button>
        <el-button
            class="main-btn"
            size="small"
            type="primary"
            @click="handlSubmit"
        >提交审核
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, nextTick, onMounted, reactive, toRefs,} from 'vue'
import {crmStore} from '@CRM/store'
import area from '@/utils/area'
import {validateVENumber, validateVETel} from '@/utils/validate'

export default {
  name: 'FormSign',
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (validateVETel(value)) {
          callback(new Error('手机号格式不正确'))
        } else {
          callback()
        }
      }
    }
    const validateFiles = (rule, value, callback) => {
      if (data.openForm.agent.businessLicenseFiles.length === 0) {
        callback(new Error('请上传营业执照'))
      } else {
        for (
            let i = 0;
            i < data.openForm.agent.businessLicenseFiles.length;
            i++
        ) {
          const a = data.openForm.agent.businessLicenseFiles[i]
          if (a.url === '') {
            callback(new Error('请上传营业执照'))
          } else {
            callback()
          }
        }
      }
    }

    const validateNum = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        if (validateVENumber(value)) {
          callback(new Error('格式不正确(最多保留两位小数)'))
        } else {
          callback()
        }
      }
    }
    //* ********************************
    const api = inject('api')
    var data = reactive({
      openBoole: false,
      cityList: area,
      openForm: {
        value: '',
        date: null,
        agent: {
          id: null,
          agentLevel: '', // 代理级别
          agentName: '', // 名称
          agentNumber: '', // 编号
          creditCode: '', //
          provinceCode: '',
          cityCode: '',
          areaCode: '',
          address: '',
          userName: '',
          tel: '',
          businessLicenseFiles: [],
        },
        contract: {
          contractName: '',
          contractObjectType: 'agent',
          contractBeginTime: '',
          contractEndTime: '',
          contractHeadName: '', // 合同负责人
          contractHeadId: null, // 合同负责人id
          contractDepartmentName: '', // 合同归属部门
          contractDepartmentId: null, // 合同归属部门
          contractAmount: null,
          contractFile: [],
        },
      },
      openRef: null,
      title: '潜在代理商签约开户',
      rules: {
        'agent.agentName': [
          {required: true, message: '请输入终端名称', trigger: 'blur'},
        ],
        'agent.creditCode': [
          {required: true, message: '请输统一社会信用代码', trigger: 'blur'},
        ],
        'agent.agentLevel': [
          {required: true, message: '请选择代理商级别', trigger: 'change'},
        ],
        'agent.address': [
          {required: true, message: '请输入详细地址', trigger: 'blur'},
        ],
        'agent.tel': [
          {required: true, validator: validateTel, trigger: 'blur'},
        ],
        'agent.userName': [
          {required: true, message: '请输入联系人', trigger: 'blur'},
        ],
        value: [{required: true, message: '请选择地区', trigger: 'change'}],
        date: [
          {required: true, message: '请选择合同日期', trigger: 'change'},
        ],
        'contract.contractName': [
          {required: true, message: '请输入合同名称', trigger: 'blur'},
        ],
        'contract.contractAmount': [
          {validator: validateNum, trigger: 'blur'},
        ],
        'agent.businessLicenseFiles': [
          {required: true, validator: validateFiles, trigger: 'change'},
        ],
      },
      contractTypeData:
          crmStore.getters['dictionary/getDictionary']['contract_type'],
      contractObjectTypeData:
          crmStore.getters['dictionary/getDictionary']['contract_object'],
      agentlevelData:
          crmStore.getters['dictionary/getDictionary']['agent_level'],
      headList: [],
      departmentList: [],
    })
    const currentInstance = getCurrentInstance()

    const handlCity = (val) => {
      if (val) {
        data.openForm.agent.provinceCode = val[0]
        data.openForm.agent.cityCode = val[1]
        data.openForm.agent.areaCode = val[2]
        nextTick((_) => {
          data.openRef.clearValidate('provinceCode')
        })
      }
    }

    const handlDate = (val) => {
      if (val) {
        data.openForm.contract.contractBeginTime = val[0]
        data.openForm.contract.contractEndTime = val[1]
      }
    }

    const handlAmount = (val) => {
      data.openForm.contract.contractAmount = Number(val)
    }

    const close = () => {
      data.openBoole = false
      handlRemove()
    }

    const handlRemove = () => {
      data.openForm.cityCode = ''
      data.openForm.areaCode = ''
      data.openForm.address = ''
      data.openRef.clearValidate()
      data.openRef.resetFields()
    }

    const open = (val) => {
      if (val) {
        handlDetail(val)
      }
    }

    const handlFile = () => {
      data.openForm.contract.contractFile.forEach((item) => {
        item.code = ''
        item.isLong = 1
        item.isNeed = 1
        item.type = 1
        item.validTime = ''
      })
    }

    const handlSubmit = () => {
      handlFile()
      data.openRef.validate((valid) => {
        if (valid) {
          api.channelAgent
              .POTENTIALAGENT_OPEN_ACCOUNT(data.openForm)
              .then((res) => {
                if (res.code === 0) {
                  currentInstance.proxy.customMessage({
                    type: 'success',
                    message: '创建成功',
                  })
                  context.emit('succsessFormSign')
                  close()
                } else {
                  currentInstance.proxy.customMessage({
                    type: 'error',
                    message: res.msg,
                  })
                }
              })
        }
      })
    }

    const handlDetail = async (id) => {
      const dataContract = {
        objectId: Number(id),
        contractObjectType: 'agent',
      }

      const resCon = await api.channelAgent.CONTRACT_EFFECTIVE(dataContract)
      if (resCon.code === 0) {
        if (resCon.data.list.length === 0) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message:
                '当前代理商无代理合同，无法提交签约开户审核，请创建代理合同后再提交',
          })
        } else {
          data.openBoole = true
        }
      }

      const res = await api.channelAgent.POTENTIALAGENT_DETAIL(id)
      if (res.code === 0) {
        const dataAgent = reactive(res.data.agent)
        for (const key in data.openForm.agent) {
          data.openForm['agent'][key] = dataAgent[key]
        }
        if (
            data.openForm['agent']['businessLicenseFiles'] &&
            data.openForm['agent']['businessLicenseFiles'].length === 0
        ) {
          data.openForm.agent.businessLicenseFiles =
              crmStore.getters['jsonData/getJsonData']['agent_qualification'].data
        }
        data.openForm.value = [
          data.openForm.agent.provinceCode,
          data.openForm.agent.cityCode,
          data.openForm.agent.areaCode,
        ]
      }

      // let ress = await api.channelAgent.POTENTIALAGENT_CONTRACT_DETAIL(id)
      // if (ress.code === 0) {
      //   let dataContract = reactive(ress.data.contract)
      //   for (let key in data.openForm.contract) {
      //     data.openForm.contract[key] = dataContract[key]
      //   }
      //   data.openForm.contract.id = dataContract.id
      //   data.openForm.date = [data.openForm.contract.contractBeginTime, data.openForm.contract.contractEndTime]
      //
      // }
    }

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          data.headList = res.data
        }
      })
    }

    const handlChangeHead = (val) => {
      const index = data.headList.findIndex((a) => a.id === val)
      if (index !== -1) {
        data.openForm.contractHeadName = data.headList[index].userName
      }
    }

    const handlDepartment = () => {
      api.terminal.DEPARTMENT_LIST().then((res) => {
        if (res.code === 0) {
          data.departmentList = res.data
        }
      })
    }

    const handlCascader = (val) => {
      if (val) {
        const a = handlRecursive(data.departmentList, val[val.length - 1])
        data.openForm.contract.contractDepartmentId = a[a.length - 1].id
        data.openForm.contract.contractDepartmentName = a[a.length - 1].name
      }
    }

    const handlRecursive = (arr, id) => {
      let oldList = []
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i].parentId) {
          oldList.push({id: arr[i].parentId, name: arr[i].deptName})
          return oldList
        } else if (arr[i].children && arr[i].children.length > 0) {
          const newList = handlRecursive(arr[i].children, id)
          if (newList && newList.length > 0) {
            oldList.push({id: arr[i].parentId, name: arr[i].deptName})
            oldList = oldList.concat(newList)
            return oldList
          }
        }
      }
    }

    onMounted((_) => {
      handlHead()
      handlDepartment()
    })

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlCity,
      handlRemove,
      handlDate,
      handlAmount,
      handlDetail,
      handlFile,
      handlChangeHead,
      handlDepartment,
      handlCascader,
    }
  },
}
</script>

<style lang="scss" scoped>
</style>
